# coding: utf-8
# @Time: 2022-05-09
# @File: zip_file.py
# @Author: cyl
import os
import zipfile

absFileList: list = []


def getAllFile(file_dir):
    """获取文件夹下所有文件"""
    dir_list = os.listdir(file_dir)
    for cur_file in dir_list:
        path = os.path.join(file_dir, cur_file)  # 获取文件的绝对路径
        if os.path.isfile(path):  # 判断是否是文件还是目录, 需要用绝对路径
            absFileList.append(path)
        if os.path.isdir(path):
            getAllFile(path)  # 递归子目录


def zipWriteMyFile(zipFilePath, listOfFilePaths, mode):
    """
    将文件（列表形式）直接写入zip
    :param zipFilePath: 写入的zip文件地址
    :param listOfFilePaths: 文件地址列表
    :param mode: 文件写入方式 str
    """
    zf = zipfile.ZipFile(zipFilePath, mode, zipfile.ZIP_DEFLATED)
    for path in listOfFilePaths:
        filename = os.path.basename(os.path.normpath(path))
        zf.write(path, filename)
    zf.close()


def zipDir(dirname, zipFileName):
    """
    压缩文件夹为zip
    :param dirname: 文件夹目录
    :param zipFileName: 压缩后的文件夹目录
    """
    fileList = []
    if os.path.isfile(dirname):
        fileList.append(dirname)
    else:
        for root, dirs, files in os.walk(dirname):
            for name in files:
                fileList.append(os.path.join(root, name))
                zf = zipfile.ZipFile(zipFileName, "w", zipfile.zlib.DEFLATED)
                for tar in fileList:
                    arc_name = tar[len(dirname):]
                    zf.write(tar, arc_name)
                zf.close()


# if __name__ == "__main__":
#     getAllFile(r'D:\projects\casqualityclient\syn_form\2022平武质检模板库-20220509163659274\2022平武质检模板库\1 表格说明及通用表格（第一册）')
#     print(fileAbsFileList, '\n', len(fileAbsFileList))

#     zipDir(r'D:\projects\casqualityclient\syn_form\2022平武质检模板库-20220509194928825\2022平武质检模板库\1 表格说明及通用表格（第一册）',
#            r'D:\projects\casqualityclient\syn_form\testzip.zip')

#     zipWriteMyFile("123.zip", absFileList)
